package org.ravenhearte.engine.gui;

import org.ravenhearte.engine.input.InputEvent;
import org.ravenhearte.engine.input.InputEventManager;
import org.ravenhearte.engine.input.InputEvent.EventType;
import org.ravenhearte.engine.input.InputEventManager.Queue;

import com.jme.renderer.ColorRGBA;
import com.jme.scene.shape.Quad;
import com.jme.system.DisplaySystem;

public class GUITitleBar extends GUIElement {
	/**
	 * 
	 */
	private static final long serialVersionUID = -3318438374194819267L;
	GUIElement GUIparent;

	public GUITitleBar(GUIElement parent, String text, ColorRGBA color, int width, int height) {
		super("TitleBar " + text);
		
		GUIparent = parent;

		mesh = new Quad(name + "'s Mesh", width, height);
		mesh.setSolidColor(color);
		
		attachChild(mesh);
		
		loadEvents();
	}

	@Override
	public boolean onEvent(InputEvent ev) {
		switch (ev.type) {
		case CUSTOM:
			if (ev.textId.contentEquals("MousePress " + name + "'s Mesh")) {
				switch (ev.id) {
				case 0:
					InputEvent evnt = new InputEvent();
					evnt.parent = this;
					evnt.type = EventType.MOVE;
					evnt.id = 0;
					InputEventManager.eM.registerEvent(Queue.GUI, evnt);
					
					evnt = new InputEvent();
					evnt.parent = this;
					evnt.type = EventType.BUTTONUP;
					evnt.id = 0;
					InputEventManager.eM.registerEvent(Queue.GUI, evnt);
					
					return true;
				}
			}
			break;
		case BUTTONUP:
			InputEventManager.eM.unregisterEvent(this, EventType.MOVE, 0);
			InputEventManager.eM.unregisterEvent(this, EventType.BUTTONUP, 0);
			return true;
		case MOVE:
			DisplaySystem display = DisplaySystem.getDisplaySystem();
			if (ev.x > 0 && ev.x < display.getWidth()-1 &&
					ev.y > 0 && ev.y < display.getHeight()-1) {
				InputEvent evnt = new InputEvent();
				evnt.parent = this;
				evnt.type = EventType.CUSTOM;
				evnt.textId = "Move " + GUIparent.getName();
				evnt.delta = ev.delta;
				evnt.delta2 = ev.delta2;
				InputEventManager.eM.generateEvent(evnt);
				return true;
			}
			break;
		}
		
		return false;
	}
	
	private void loadEvents() {
		InputEvent evnt = new InputEvent();
		evnt.parent = this;
		evnt.type = EventType.CUSTOM;
		evnt.textId = "MousePress " + name + "'s Mesh";
		evnt.id = 0;
		InputEventManager.eM.registerEvent(Queue.GUI, evnt);
	}

	@Override
	public void unloadEvents() {
		InputEventManager.eM.unregisterEvents(this);
	}
}